<template>
  <div class="dashboard">
    <!-- 页面标题 -->
    <div class="page-title">6月统计数据</div>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stats-row">
      <!-- 商品总数卡片 -->
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">商品总数</div>
            <div class="stat-value">{{ totalGoods }}</div>
            <div class="stat-trend">
              <span class="increase">+{{ goodsGrowth }}%</span>
              <span class="text">较上月</span>
            </div>
          </div>
          <div class="stat-icon orange">
            <Goods />
          </div>
        </el-card>
      </el-col>

      <!-- 商品分类卡片 -->
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">商品分类数量</div>
            <div class="stat-value">{{ totalCategories }}</div>
            <div class="stat-trend">
              <span class="increase">+{{ categoryGrowth }}%</span>
              <span class="text">较上月</span>
            </div>
          </div>
          <div class="stat-icon purple">
            <Menu />
          </div>
        </el-card>
      </el-col>

      <!-- 用户访问卡片 -->
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">用户访问次数</div>
            <div class="stat-value">{{ visitCount }}</div>
            <div class="stat-trend">
              <span class="decrease">-{{ visitDrop }}%</span>
              <span class="text">较上月</span>
            </div>
          </div>
          <div class="stat-icon blue">
            <UserFilled />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 刷新按钮 -->
      <el-col :span="24" style="margin-bottom: 10px; text-align: right;">
        <el-button type="primary" @click="fetchData">
          <Refresh /> 刷新数据
        </el-button>
      </el-col>

      <!-- 销售额折线图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">2022年月度销售额（万元）</div>
          <div class="chart-container">
            <div id="salesChart" class="chart" />
          </div>
        </el-card>
      </el-col>

      <!-- 订单数量柱状图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">2022年订单数量（单）</div>
          <div class="chart-container">
            <div id="orderChart" class="chart" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import { getDashboardData } from '../api/dashboard'; // 导入接口
import { Goods, Menu, UserFilled, Refresh } from '@element-plus/icons-vue';

// 统计卡片数据（响应式）
const totalGoods = ref(0);
const goodsGrowth = ref(0);
const totalCategories = ref(0);
const categoryGrowth = ref(0);
const visitCount = ref(0);
const visitDrop = ref(0);

// 图表实例存储
let salesChartInstance = null;
let orderChartInstance = null;

/**
 * 数据请求核心方法（含错误处理和模拟数据）
 */
const fetchData = async () => {
  try {
    // 调用接口获取真实数据
    const { data } = await getDashboardData({ month: '2022-06' });

    // 接口成功：更新统计卡片
    totalGoods.value = data.totalGoods;
    goodsGrowth.value = data.goodsGrowth;
    totalCategories.value = data.totalCategories;
    categoryGrowth.value = data.categoryGrowth;
    visitCount.value = data.visitCount;
    visitDrop.value = data.visitDrop;

    // 更新图表数据
    updateCharts(data.salesData, data.orderData);
  } catch (error) {
    // 接口失败：打印错误并使用模拟数据
    console.error('数据请求失败，切换到模拟数据：', error);
    const mockData = {
      totalGoods: 500,
      goodsGrowth: 12.5,
      totalCategories: 20,
      categoryGrowth: 2.1,
      visitCount: 121,
      visitDrop: 3.2,
      salesData: [5, 7, 8, 8, 10, 12, 13, 12, 14, 13, 14, 15], // 月度销售额
      orderData: [400, 450, 300, 250, 200, 300, 400, 550, 350, 150, 380, 400] // 月度订单数
    };

    // 模拟数据更新统计卡片
    totalGoods.value = mockData.totalGoods;
    goodsGrowth.value = mockData.goodsGrowth;
    totalCategories.value = mockData.totalCategories;
    categoryGrowth.value = mockData.categoryGrowth;
    visitCount.value = mockData.visitCount;
    visitDrop.value = mockData.visitDrop;

    // 模拟数据更新图表
    updateCharts(mockData.salesData, mockData.orderData);
  }
};

/**
 * 初始化图表实例
 */
const initCharts = () => {
  // 销售额图表
  const salesDom = document.getElementById('salesChart');
  if (salesDom && !salesChartInstance) {
    salesChartInstance = echarts.init(salesDom);
  }

  // 订单图表
  const orderDom = document.getElementById('orderChart');
  if (orderDom && !orderChartInstance) {
    orderChartInstance = echarts.init(orderDom);
  }
};

/**
 * 更新图表数据
 * @param {Array} salesData - 销售额数组
 * @param {Array} orderData - 订单数数组
 */
const updateCharts = (salesData, orderData) => {
  // 确保图表实例已创建
  if (!salesChartInstance || !orderChartInstance) {
    initCharts();
  }

  // 更新销售额折线图
  salesChartInstance.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: { type: 'value' },
    series: [{
      data: salesData,
      type: 'line',
      smooth: true,
      lineStyle: { color: '#409eff' },
      animationDuration: 1000
    }]
  });

  // 更新订单柱状图
  orderChartInstance.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: { type: 'value' },
    series: [{
      data: orderData,
      type: 'bar',
      itemStyle: { color: '#6b7280' },
      animationDuration: 1000
    }]
  });
};

// 页面挂载时初始化
onMounted(() => {
  // 确保DOM加载完成
  setTimeout(() => {
    initCharts(); // 初始化图表
    fetchData(); // 首次加载数据
    setInterval(fetchData, 30000); // 每30秒自动刷新
  }, 100);

  // 监听窗口大小变化，调整图表尺寸
  window.addEventListener('resize', () => {
    salesChartInstance?.resize();
    orderChartInstance?.resize();
  });
});
</script>

<style scoped>
.dashboard {
  padding: 20px;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #1f2937;
}

/* 统计卡片样式 */
.stats-row { margin-bottom: 20px; }

.stat-card {
  height: 150px;
  display: flex;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.stat-item { flex: 1; }

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #1f2937;
}

.stat-trend { display: flex; align-items: center; gap: 5px; }

.increase { color: #10b981; font-size: 12px; }

.decrease { color: #ef4444; font-size: 12px; }

.text { color: #6b7280; font-size: 12px; }

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.orange { background-color: #fef3c7; color: #d97706; }

.purple { background-color: #f3e8ff; color: #8b5cf6; }

.blue { background-color: #dbeafe; color: #3b82f6; }

/* 图表区域样式 */
.charts-row { margin-top: 20px; }

.chart-card {
  height: 400px !important;
  overflow: hidden;
}

.chart-container {
  width: 100%;
  height: calc(100% - 40px);
  min-height: 360px;
  box-sizing: border-box;
}

.chart {
  width: 100%;
  height: 400px; /* 明确高度 */
  min-height: 300px;
}
</style>